import { createRouter, createWebHistory } from 'vue-router'

const routes = [
    {
        path: '/',
        redirect: '/login-admin'
    },
    {
        path: '/login-admin',
        name: 'LoginAdmin',
        component: () => import('../views/LoginAdmin.vue'),
        meta: { title: '管理员登录' }
    },
    {
        path: '/login',
        name: 'Login',
        component: () => import('../views/Login.vue'),
        meta: { title: '学生登录' }
    },
    {
        path: '/index',
        name: 'Index',
        component: () => import('../views/Index.vue'),
        meta: { title: '首页' }
    },
    {
        path: '/profile',
        name: 'Profile',
        component: () => import('../views/Profile.vue'),
        meta: { title: '个人中心' }
    },
    {
        path: '/admin',
        name: 'Admin',
        component: () => import('../views/Admin.vue'),
        meta: { title: '管理后台' },
        children: [
            {
                path: 'idle',
                name: 'IdleManage',
                component: () => import('../views/admin/IdleManage.vue'),
                meta: { title: '闲置管理' }
            },
            {
                path: 'order',
                name: 'OrderManage',
                component: () => import('../views/admin/OrderManage.vue'),
                meta: { title: '订单管理' }
            },
            {
                path: 'user',
                name: 'UserManage',
                component: () => import('../views/admin/UserManage.vue'),
                meta: { title: '用户管理' }
            }
        ]
    },
    // 捕获所有未定义路由重定向到登录页
    {
        path: '/:pathMatch(.*)*',
        redirect: '/login-admin'
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

// 路由守卫 - 权限检查
router.beforeEach((to, from, next) => {
    // 简单的登录检查
    const adminInfo = sessionStorage.getItem('adminInfo')
    const userInfo = sessionStorage.getItem('userInfo')
    
    // 管理员页面需要登录
    if (to.path.startsWith('/admin') && !adminInfo) {
        next('/login-admin')
        return
    }
    
    // 用户首页需要登录
    if (to.path === '/index' && !userInfo) {
        next('/login')
        return
    }
    
    next()
})

export default router
